subversion.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # The following comment should be removed at some point in the future.
  2. # mypy: disallow-untyped-defs=False
  3. from __future__ import absolute_import
  4. import logging
  5. import os
  6. import re
  7. from pip._internal.utils.logging import indent_log
  8. from pip._internal.utils.misc import (
  9. display_path,
  10. is_console_interactive,
  11. rmtree,
  12. split_auth_from_netloc,
  13. )
  14. from pip._internal.utils.subprocess import make_command
  15. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  16. from pip._internal.vcs.versioncontrol import VersionControl, vcs
  17. _svn_xml_url_re = re.compile('url="([^"]+)"')
  18. _svn_rev_re = re.compile(r'committed-rev="(\d+)"')
  19. _svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"')
  20. _svn_info_xml_url_re = re.compile(r'<url>(.*)</url>')
  21. if MYPY_CHECK_RUNNING:
  22. from typing import Optional, Tuple
  23. from pip._internal.utils.subprocess import CommandArgs
  24. from pip._internal.utils.misc import HiddenText
  25. from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions
  26. logger = logging.getLogger(__name__)
  27. class Subversion(VersionControl):
  28. name = 'svn'
  29. dirname = '.svn'
  30. repo_name = 'checkout'
  31. schemes = ('svn', 'svn+ssh', 'svn+http', 'svn+https', 'svn+svn')
  32. @classmethod
  33. def should_add_vcs_url_prefix(cls, remote_url):
  34. return True
  35. @staticmethod
  36. def get_base_rev_args(rev):
  37. return ['-r', rev]
  38. @classmethod
  39. def get_revision(cls, location):
  40. """
  41. Return the maximum revision for all files under a given location
  42. """
  43. # Note: taken from setuptools.command.egg_info
  44. revision = 0
  45. for base, dirs, _ in os.walk(location):
  46. if cls.dirname not in dirs:
  47. dirs[:] = []
  48. continue # no sense walking uncontrolled subdirs
  49. dirs.remove(cls.dirname)
  50. entries_fn = os.path.join(base, cls.dirname, 'entries')
  51. if not os.path.exists(entries_fn):
  52. # FIXME: should we warn?
  53. continue
  54. dirurl, localrev = cls._get_svn_url_rev(base)
  55. if base == location:
  56. base = dirurl + '/' # save the root url
  57. elif not dirurl or not dirurl.startswith(base):
  58. dirs[:] = []
  59. continue # not part of the same svn tree, skip it
  60. revision = max(revision, localrev)
  61. return revision
  62. @classmethod
  63. def get_netloc_and_auth(cls, netloc, scheme):
  64. """
  65. This override allows the auth information to be passed to svn via the
  66. --username and --password options instead of via the URL.
  67. """
  68. if scheme == 'ssh':
  69. # The --username and --password options can't be used for
  70. # svn+ssh URLs, so keep the auth information in the URL.
  71. return super(Subversion, cls).get_netloc_and_auth(netloc, scheme)
  72. return split_auth_from_netloc(netloc)
  73. @classmethod
  74. def get_url_rev_and_auth(cls, url):
  75. # type: (str) -> Tuple[str, Optional[str], AuthInfo]
  76. # hotfix the URL scheme after removing svn+ from svn+ssh:// readd it
  77. url, rev, user_pass = super(Subversion, cls).get_url_rev_and_auth(url)
  78. if url.startswith('ssh://'):
  79. url = 'svn+' + url
  80. return url, rev, user_pass
  81. @staticmethod
  82. def make_rev_args(username, password):
  83. # type: (Optional[str], Optional[HiddenText]) -> CommandArgs
  84. extra_args = [] # type: CommandArgs
  85. if username:
  86. extra_args += ['--username', username]
  87. if password:
  88. extra_args += ['--password', password]
  89. return extra_args
  90. @classmethod
  91. def get_remote_url(cls, location):
  92. # In cases where the source is in a subdirectory, not alongside
  93. # setup.py we have to look up in the location until we find a real
  94. # setup.py
  95. orig_location = location
  96. while not os.path.exists(os.path.join(location, 'setup.py')):
  97. last_location = location
  98. location = os.path.dirname(location)
  99. if location == last_location:
  100. # We've traversed up to the root of the filesystem without
  101. # finding setup.py
  102. logger.warning(
  103. "Could not find setup.py for directory %s (tried all "
  104. "parent directories)",
  105. orig_location,
  106. )
  107. return None
  108. return cls._get_svn_url_rev(location)[0]
  109. @classmethod
  110. def _get_svn_url_rev(cls, location):
  111. from pip._internal.exceptions import SubProcessError
  112. entries_path = os.path.join(location, cls.dirname, 'entries')
  113. if os.path.exists(entries_path):
  114. with open(entries_path) as f:
  115. data = f.read()
  116. else: # subversion >= 1.7 does not have the 'entries' file
  117. data = ''
  118. if (data.startswith('8') or
  119. data.startswith('9') or
  120. data.startswith('10')):
  121. data = list(map(str.splitlines, data.split('\n\x0c\n')))
  122. del data[0][0] # get rid of the '8'
  123. url = data[0][3]
  124. revs = [int(d[9]) for d in data if len(d) > 9 and d[9]] + [0]
  125. elif data.startswith('<?xml'):
  126. match = _svn_xml_url_re.search(data)
  127. if not match:
  128. raise ValueError(
  129. 'Badly formatted data: {data!r}'.format(**locals()))
  130. url = match.group(1) # get repository URL
  131. revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]
  132. else:
  133. try:
  134. # subversion >= 1.7
  135. # Note that using get_remote_call_options is not necessary here
  136. # because `svn info` is being run against a local directory.
  137. # We don't need to worry about making sure interactive mode
  138. # is being used to prompt for passwords, because passwords
  139. # are only potentially needed for remote server requests.
  140. xml = cls.run_command(
  141. ['info', '--xml', location],
  142. )
  143. url = _svn_info_xml_url_re.search(xml).group(1)
  144. revs = [
  145. int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)
  146. ]
  147. except SubProcessError:
  148. url, revs = None, []
  149. if revs:
  150. rev = max(revs)
  151. else:
  152. rev = 0
  153. return url, rev
  154. @classmethod
  155. def is_commit_id_equal(cls, dest, name):
  156. """Always assume the versions don't match"""
  157. return False
  158. def __init__(self, use_interactive=None):
  159. # type: (bool) -> None
  160. if use_interactive is None:
  161. use_interactive = is_console_interactive()
  162. self.use_interactive = use_interactive
  163. # This member is used to cache the fetched version of the current
  164. # ``svn`` client.
  165. # Special value definitions:
  166. # None: Not evaluated yet.
  167. # Empty tuple: Could not parse version.
  168. self._vcs_version = None # type: Optional[Tuple[int, ...]]
  169. super(Subversion, self).__init__()
  170. def call_vcs_version(self):
  171. # type: () -> Tuple[int, ...]
  172. """Query the version of the currently installed Subversion client.
  173. :return: A tuple containing the parts of the version information or
  174. ``()`` if the version returned from ``svn`` could not be parsed.
  175. :raises: BadCommand: If ``svn`` is not installed.
  176. """
  177. # Example versions:
  178. # svn, version 1.10.3 (r1842928)
  179. # compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0
  180. # svn, version 1.7.14 (r1542130)
  181. # compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu
  182. # svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)
  183. # compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2
  184. version_prefix = 'svn, version '
  185. version = self.run_command(['--version'])
  186. if not version.startswith(version_prefix):
  187. return ()
  188. version = version[len(version_prefix):].split()[0]
  189. version_list = version.partition('-')[0].split('.')
  190. try:
  191. parsed_version = tuple(map(int, version_list))
  192. except ValueError:
  193. return ()
  194. return parsed_version
  195. def get_vcs_version(self):
  196. # type: () -> Tuple[int, ...]
  197. """Return the version of the currently installed Subversion client.
  198. If the version of the Subversion client has already been queried,
  199. a cached value will be used.
  200. :return: A tuple containing the parts of the version information or
  201. ``()`` if the version returned from ``svn`` could not be parsed.
  202. :raises: BadCommand: If ``svn`` is not installed.
  203. """
  204. if self._vcs_version is not None:
  205. # Use cached version, if available.
  206. # If parsing the version failed previously (empty tuple),
  207. # do not attempt to parse it again.
  208. return self._vcs_version
  209. vcs_version = self.call_vcs_version()
  210. self._vcs_version = vcs_version
  211. return vcs_version
  212. def get_remote_call_options(self):
  213. # type: () -> CommandArgs
  214. """Return options to be used on calls to Subversion that contact the server.
  215. These options are applicable for the following ``svn`` subcommands used
  216. in this class.
  217. - checkout
  218. - export
  219. - switch
  220. - update
  221. :return: A list of command line arguments to pass to ``svn``.
  222. """
  223. if not self.use_interactive:
  224. # --non-interactive switch is available since Subversion 0.14.4.
  225. # Subversion < 1.8 runs in interactive mode by default.
  226. return ['--non-interactive']
  227. svn_version = self.get_vcs_version()
  228. # By default, Subversion >= 1.8 runs in non-interactive mode if
  229. # stdin is not a TTY. Since that is how pip invokes SVN, in
  230. # call_subprocess(), pip must pass --force-interactive to ensure
  231. # the user can be prompted for a password, if required.
  232. # SVN added the --force-interactive option in SVN 1.8. Since
  233. # e.g. RHEL/CentOS 7, which is supported until 2024, ships with
  234. # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip
  235. # can't safely add the option if the SVN version is < 1.8 (or unknown).
  236. if svn_version >= (1, 8):
  237. return ['--force-interactive']
  238. return []
  239. def export(self, location, url):
  240. # type: (str, HiddenText) -> None
  241. """Export the svn repository at the url to the destination location"""
  242. url, rev_options = self.get_url_rev_options(url)
  243. logger.info('Exporting svn repository %s to %s', url, location)
  244. with indent_log():
  245. if os.path.exists(location):
  246. # Subversion doesn't like to check out over an existing
  247. # directory --force fixes this, but was only added in svn 1.5
  248. rmtree(location)
  249. cmd_args = make_command(
  250. 'export', self.get_remote_call_options(),
  251. rev_options.to_args(), url, location,
  252. )
  253. self.run_command(cmd_args)
  254. def fetch_new(self, dest, url, rev_options):
  255. # type: (str, HiddenText, RevOptions) -> None
  256. rev_display = rev_options.to_display()
  257. logger.info(
  258. 'Checking out %s%s to %s',
  259. url,
  260. rev_display,
  261. display_path(dest),
  262. )
  263. cmd_args = make_command(
  264. 'checkout', '-q', self.get_remote_call_options(),
  265. rev_options.to_args(), url, dest,
  266. )
  267. self.run_command(cmd_args)
  268. def switch(self, dest, url, rev_options):
  269. # type: (str, HiddenText, RevOptions) -> None
  270. cmd_args = make_command(
  271. 'switch', self.get_remote_call_options(), rev_options.to_args(),
  272. url, dest,
  273. )
  274. self.run_command(cmd_args)
  275. def update(self, dest, url, rev_options):
  276. # type: (str, HiddenText, RevOptions) -> None
  277. cmd_args = make_command(
  278. 'update', self.get_remote_call_options(), rev_options.to_args(),
  279. dest,
  280. )
  281. self.run_command(cmd_args)
  282. vcs.register(Subversion)